﻿using KwaiXiaoDian.Common;
using KwaiXiaoDian.Entity.Common;
using KwaiXiaoDian.Entity.DO;
using KwaiXiaoDian.Entity.VO.User;
using KwaiXiaoDian.IDao;
using KwaiXiaoDian.IService;
using SSharing.Frameworks.NetCore.Common.Consts;
using SSharing.Frameworks.NetCore.Common.Extends;
using SSharing.Frameworks.NetCore.Common.Results;
using System;
using System.Collections.Generic;
using System.Linq;

namespace KwaiXiaoDian.Service
{
    /// <summary>
    /// 用户service
    /// </summary>
    public class UserService : BaseService<TUser>, IUserService
    {
        private readonly IUserDao _userDao;
        private const string DEFAULT_PASSWD = "Abc@123456";

        public UserService(IUserDao userDao) : base(userDao)
        {
            _userDao = userDao;
        }

        public Tuple<bool, string> Add(AddUserRequest request)
        {
            bool addUserSuccess = false;
            string errorMsg = "";
            var now = DateTime.Now;

            //校验手机号是否存在
            var phoneNumber = request.PhoneNumber.Trim();
            var list = _userDao.Get(p => p.IsEnabled == Enums.IsEnabledType.Y.ToString() && p.PhoneNumber == phoneNumber);
            if (list.HasValue())
            {
                errorMsg = "该手机号已存在!";
                return new Tuple<bool, string>(addUserSuccess, errorMsg);
            }

            var passwd = DEFAULT_PASSWD.ToMD5With32bit();
            var addResult = _userDao.Add(new TUser
            {
                CreatedTime = now,
                CreatedBy = -1,
                LastUpdatedTime = now,
                LastUpdatedBy = -1,
                IsEnabled = Enums.IsEnabledType.Y.ToString(),
                PhoneNumber = phoneNumber,
                Email = request.Email,
                NickName = request.NickName,
                Passwd = passwd,
                Role = request.Role
            });
            if (addResult == true)
            {
                addUserSuccess = true;
            }

            return new Tuple<bool, string>(addUserSuccess, errorMsg);
        }

        public Tuple<bool, string> DisableUser(DisableUserRequest request)
        {
            bool disableUserSuccess = false;
            string errorMsg = "";
            var now = DateTime.Now;

            var user = _userDao.Get(p => p.Id == request.Id).First();
            if (user != null)
            {
                user.LastUpdatedBy = -1;
                user.LastUpdatedTime = now;
                user.IsEnabled = request.IsEnabled;

                var updateResult = _userDao.Update(user);
                if (updateResult == true)
                {
                    disableUserSuccess = true;
                }
            }

            return new Tuple<bool, string>(disableUserSuccess, errorMsg);
        }

        public IPagingResult<UserModel> GetPagingUsers(GetPagingUsersRequest request)
        {
            List<UserModel> list = new List<UserModel>();
            var pagingUsers = _userDao.GetPagingUsers(request);
            if (pagingUsers == null || !pagingUsers.Entities.HasValue())
            {
                return new PagingResult<UserModel>(pagingUsers.TotalCount, request.Page, request.Limit, list);
            }

            foreach (var item in pagingUsers.Entities)
            {
                list.Add(new UserModel
                {
                    Id = item.Id,
                    CreatedTime = item.CreatedTime.ToString(DateTimeTypeConst.DATETIME),
                    CreatedBy = item.CreatedBy,
                    IsEnabled = item.IsEnabled,
                    PhoneNumber = item.PhoneNumber,
                    Email = item.Email,
                    NickName = item.NickName,
                    Role = item.Role
                });
            }

            return new PagingResult<UserModel>(pagingUsers.TotalCount, request.Page, request.Limit, list);
        }

        public IList<UserMenu> GetUserMenus(string role)
        {
            IList<UserMenu> userMenus = new List<UserMenu>();

            //首页
            userMenus.Add(new UserMenu
            {
                Name = "home",
                Title = "首页",
                Icon = "layui-icon-home",
                Jump = "",
                Spread = false,
                SubMenus = new List<UserMenu>()
                {
                    new UserMenu
                    {
                        Name = "console",
                        Title = "控制台",
                        Jump = "/",
                        Spread = false,
                        SubMenus= new List<UserMenu>()
                    }
                }
            });

            //团长管理
            userMenus.Add(new UserMenu
            {
                Name = "leader",
                Title = "团长管理",
                Icon = "layui-icon-group",
                Jump = "",
                Spread = false,
                SubMenus = new List<UserMenu>()
                {
                    new UserMenu
                    {
                        Name = "list",
                        Title = "团长管理",
                        Jump = "",
                        Spread = false,
                        SubMenus= new List<UserMenu>()
                    }
                }
            });

            //商品管理
            userMenus.Add(new UserMenu
            {
                Name = "product",
                Title = "商品管理",
                Icon = "layui-icon-cart",
                Jump = "",
                Spread = false,
                SubMenus = new List<UserMenu>()
                {
                    new UserMenu
                    {
                        Name = "list",
                        Title = "商品管理",
                        Jump = "",
                        Spread = false,
                        SubMenus= new List<UserMenu>()
                    }
                }
            });

            //var roleType = role.ToEnum<Enums.RoleType>();
            //if (roleType == Enums.RoleType.ADMIN)
            //{
            //    //系统管理
            //    userMenus.Add(new UserMenu
            //    {
            //        Name = "sysmanage",
            //        Title = "系统管理",
            //        Icon = "layui-icon-set",
            //        Jump = "",
            //        Spread = false,
            //        SubMenus = new List<UserMenu>()
            //    {
            //        new UserMenu
            //        {
            //            Name = "user",
            //            Title = "用户管理",
            //            Jump = "",
            //            Spread = false,
            //            SubMenus= new List<UserMenu>()
            //        }
            //    }
            //    });
            //}

            return userMenus;
        }

        public Tuple<bool, string> ResetPwd(ResetPwdRequest request, long userId)
        {
            var resetPwdSuccess = false;
            var errorMessage = string.Empty;
            var now = DateTime.Now;

            var user = _userDao.Get(request.Id);
            if (user == null)
            {
                errorMessage = "用户id有误!";
                return new Tuple<bool, string>(resetPwdSuccess, errorMessage);
            }

            //生成随机密码
            var newPwd = KwaiXiaoDianHelper.GenerateUserPassword();
            var cryptPwd = newPwd.ToMD5With32bit();

            user.LastUpdatedBy = userId;
            user.LastUpdatedTime = now;
            user.Passwd = cryptPwd;
            resetPwdSuccess = _userDao.Update(user);
            if (resetPwdSuccess != true)
            {
                errorMessage = "重置密码失败.";
                return new Tuple<bool, string>(resetPwdSuccess, errorMessage);
            }

            errorMessage = string.Format("已将：{0}的密码重置为：{1}", user.PhoneNumber, newPwd);
            return new Tuple<bool, string>(resetPwdSuccess, errorMessage);
        }

        public Tuple<bool, string> SaveUserInfo(SaveUserInfoRequest request, long userId)
        {
            //支持修改昵称，邮箱
            bool saveUserInfoSuccess = false;
            string errorMsg = "";
            var now = DateTime.Now;

            var user = _userDao.Get(p => p.Id == request.Id).FirstOrDefault();
            if (user == null)
            {
                errorMsg = "该用户还未注册，请先注册！";
                return new Tuple<bool, string>(saveUserInfoSuccess, errorMsg);
            }

            user.LastUpdatedBy = userId;
            user.LastUpdatedTime = now;
            user.NickName = request.NickName;
            user.Email = request.Email;
            saveUserInfoSuccess = _userDao.Update(user);
            return new Tuple<bool, string>(saveUserInfoSuccess, errorMsg);
        }

        public Tuple<bool, string> Update(UpdateUserRequest request)
        {
            bool updateUserSuccess = false;
            string errorMsg = "";
            var now = DateTime.Now;

            var user = _userDao.Get(p => p.Id == request.Id).FirstOrDefault();
            if (user != null)
            {
                user.LastUpdatedBy = -1;
                user.LastUpdatedTime = now;
                user.Email = request.Email;
                user.NickName = request.NickName;
                user.Role = request.Role;

                var updateResult = _userDao.Update(user);
                if (updateResult == true)
                {
                    updateUserSuccess = true;
                }
            }

            return new Tuple<bool, string>(updateUserSuccess, errorMsg);
        }
    }
}
